/* eslint-disable */
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosHeaders } from 'axios';
import { supabase } from '@/controller/supabase';

// 基础响应接口
interface BaseResponse {
  error?: boolean;
  message?: string;
  success: boolean;
  task_id?: string;
  total?: number;
}

// 接口响应的通用格式
export type ApiResponse<T = any> = T & {
  data?: T;
} & BaseResponse;
export interface ApiError {
  error: boolean;
  success: boolean;
  message: string;
  errorMsg: string;
  errorCode: number;
  data: null;
}
// 创建请求实例
const instance: AxiosInstance = axios.create({
  baseURL: '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
instance.interceptors.request.use(
  async (config) => {
    try {
      const { data: { session } } = await supabase.auth.getSession();
      if (session?.access_token) {
        const headers = new AxiosHeaders();
        headers.set('Content-Type', 'application/json');
        headers.set('Authorization', `Bearer ${session.access_token}`);
        config.headers = headers;
      }
      return config;
    } catch (error) {
      console.error('获取认证失败:', error);
      return Promise.reject(error);
    }
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    const data = response.data;
    return {
      ...response,
      data: data
    };
  },
  (error) => {
    // 处理 401 未授权错误
    if (error.response?.status === 401) {
      window.location.href = '/auth';
      // 可以在这里添加重定向到登录页的逻辑
      console.error('认证失败，请重新登录');
    }

    return Promise.reject<ApiError>({
      error: true,
      success: false,
      message: error.response?.data?.message || error.message || '请求失败',
      errorMsg: error.response?.data?.error || "请求失败",
      errorCode: error.response?.status || 0,
      data: null
    });
  }
);

// 封装 GET 请求
export const get = async <T = any>(
  url: string,
  params?: Record<string, any>,
  config: AxiosRequestConfig = {}
): Promise<ApiResponse<T>> => {
  const finalConfig = {
    ...config,
    params
  };
  return instance.get(url, finalConfig);
};

// 封装 POST 请求
export const post = async <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<ApiResponse<T>> => {
  return instance.post(url, data, config);
};

// 封装 PUT 请求
export const put = async <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<ApiResponse<T>> => {
  return instance.put(url, data, config);
};

// 封装 DELETE 请求
export const del = async <T = any>(
  url: string,
  config?: AxiosRequestConfig
): Promise<ApiResponse<T>> => {
  return instance.delete(url, config);
};

// 封装 PATCH 请求
export const patch = async <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<ApiResponse<T>> => {
  return instance.patch(url, data, config);
};

// 导出实例，以便需要时可以直接使用
export default instance;